package com.guigu.wenzhiyi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.tankai.mapper.MemberMapper;
import com.guigu.tankai.mapper.UserMapper;
import com.guigu.tankai.pojo.Member;
import com.guigu.tankai.pojo.User;
import com.guigu.wenzhiyi.mapper.InterposefoodMapper;
import com.guigu.wenzhiyi.mapper.InterposeschemeMapper;
import com.guigu.wenzhiyi.mapper.InterposesprotMapper;
import com.guigu.wenzhiyi.pojo.Interposefood;
import com.guigu.wenzhiyi.pojo.Interposescheme;
import com.guigu.wenzhiyi.pojo.Interposesprot;
import com.guigu.wenzhiyi.service.InterposeschemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class InterposeschemeServiceImpl implements InterposeschemeService {

    @Autowired
    MemberMapper memberMapper;
    @Autowired
    InterposeschemeMapper interposeschemeMapper;
    @Autowired
    InterposefoodMapper interposefoodMapper;
    @Autowired
    InterposesprotMapper interposesprotMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public PageInfo<Member> page(Integer num, Integer size, String name) {
        PageHelper.startPage(num, size);
        List<Member> list = memberMapper.Interposeschemecha(name);
        for (Member member : list) {
            Interposescheme interposescheme = interposeschemeMapper.chaDuiXiang(member.getId());
            member.setInterposescheme(interposescheme);
            List<Interposefood> interposefoods = interposefoodMapper.listCha(member.getId());
            member.setInterposefoods(interposefoods);
            List<Interposesprot> interposesprots = interposesprotMapper.listCha(member.getId());
            member.setInterposesprots(interposesprots);
            if (member.getHiduser()!=null){
                User user = userMapper.selectByPrimaryKey(member.getHiduser());
                if (user!=null){
                    member.setUser(user);
                }
            }
        }
        return new PageInfo<>(list);
    }

    @Override
    public int add(Member member) {
        interposeschemeMapper.delete(member.getId());
        interposefoodMapper.delete(member.getId());
        interposesprotMapper.delete(member.getId());

        member.getInterposescheme().setMemberid(member.getId());
        int i = interposeschemeMapper.insert(member.getInterposescheme());
        for (Interposefood interposefood : member.getInterposefoods()) {
            interposefood.setMemberid(member.getId());
            i += interposefoodMapper.insert(interposefood);
        }
        for (Interposesprot interposesprot : member.getInterposesprots()) {
            interposesprot.setMemberid(member.getId());
            i += interposesprotMapper.insert(interposesprot);
        }

        member.setInterposeplainzt(1);
        memberMapper.zt(member);
        return i;
    }
}
